package com.example.service.impl;

import com.example.domain.LoginUser;
import com.example.domain.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service

public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userMapper.getOneByEmail(email);
        //如果为空抛出异常，security会自动捕获
        if (Objects.isNull(user)){
            throw new RuntimeException("登陆错误");
        }
        //获取权限列表
        List<String> perms = userMapper.getPerm(user.getId());
        if (CollectionUtils.isEmpty(perms)){
            throw new RuntimeException("系统异常");
        }
        return new LoginUser(user,perms);
    }
}
